package com.qf.web;

import com.qf.convert.MyConvert;
import com.qf.pojo.User;
import com.qf.service.UserService;
import com.qf.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.Map;

/**
 *更新用户
 */
@WebServlet("/updateUser")
public class UpdateUserServlet extends HttpServlet {


    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {


        //解决post提交乱码
        request.setCharacterEncoding("utf-8") ;
        //单独获取uid
        String uid = request.getParameter("uid");
        System.out.println(uid);
        //接收所有参数
        //每次接收单个request.getParameter(),太麻烦,

        //接收所有参数放在map中
        Map<String, String[]> map = request.getParameterMap();
        //BeanUtils的方法
        //ublic static void populate(Object bean, Map properties):参数1:实体,参数2:map参数
//        创建User对象
        User user = new User() ;


        //org.apache.commons.beanutils.ConversionException:
        // DateConverter does not support default String to 'Date' conversion.
        //前台封装的数据:出生日期---String
        //实体类的User的birthday Date格式

        //自定义日期转换器
        //转换器 :ConvertUtils的静态方法
        //   public static void register(Converter converter, Class clazz)
        //参数1:转换器接口:org.apache.commons.beanutils.Converter
        //参数2:Class:指定的目标类的字节码文件 Date.class
         ConvertUtils.register(new MyConvert(), Date.class);

        try {
            //封装实体类将前台参数添加User对象中
            BeanUtils.populate(user,map) ;
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
       // System.out.println(user);

        //调用业务接口
        UserService userService = new UserServiceImpl() ;
        userService.updateUser(user) ;

        //请求转发后台地址/findAllUser
        request.getRequestDispatcher("/findAllUser").forward(request,response);


    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request,response);
    }
}
